package cn.ruituo.adv9;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.List;
import java.util.Scanner;

public class XMLSearch {
    public static void main(String[] args) {

        //dom4j解析xml
        //READ
        SAXReader reader = new SAXReader();
        //相对目录
        Document doc = null;
        try {
            doc = reader.read(new File("advance/src/cn/cn.ruituo/books.xml"));
        } catch (DocumentException e) {
            System.out.println("解析失败");
            e.printStackTrace();
            return;
        }
        Scanner in = new Scanner(System.in);
        System.out.println("请输入要查找的书名：");
        String bookName = in.next();
        Element e = (Element) doc.selectSingleNode("/books/book[name='" + bookName + "']");
        if (e == null) {
            System.out.println("没有");
            return;
        }
        System.out.println("对应的book信息如下:");
        //获得属性
        String id = e.attributeValue("id");
        String diff = e.attributeValue("diff");
        //String->Integer
        //int bookid=Integer.parseInt(id);
        //Element ename= (Element) e.selectNodes("name").get(0);
        //确定最多一个name子节点
        Element ename = (Element) e.selectSingleNode("name");
        String name = ename.getText();
        Element eprice = (Element) e.selectSingleNode("price");
        String price = eprice.getText();
        Element epublishi = (Element) e.selectSingleNode("publish");
        String publish = epublishi.getText();
        Element edesc = (Element) e.selectSingleNode("description");
        String desc = edesc.getText().trim();
        System.out.printf("id=%s,diff=%s,name=%s,publish=%s,描述=%s\n", id, diff, name, publish, desc);

    }
}

